package br.com.gaspar.seam.seguranca;

import gov.sefaz.utils.exception.BaseException;

import javax.ejb.EJB;
import javax.ejb.Stateful;
import javax.inject.Inject;
import javax.inject.Named;

import org.apache.log4j.Logger;
import org.jboss.seam.security.Authenticator;
import org.jboss.seam.security.BaseAuthenticator;
import org.jboss.seam.security.Credentials;
import org.jboss.seam.security.Identity;
import org.picketlink.idm.impl.api.PasswordCredential;
import org.picketlink.idm.impl.api.model.SimpleUser;

import br.com.gaspar.bo.iface.IGasparBO;
import br.com.gaspar.entidade.Usuario;

@Stateful
@Named("Autenticador")
public class Autenticador extends BaseAuthenticator implements Authenticator{

	private static final Logger log = Logger.getLogger(Autenticador.class);
	
	@Inject
	private Credentials credentials;
	
	@Inject
	private Identity identity;
	
	@EJB
	private IGasparBO<Usuario> bo;
	
	@Override
	public void authenticate() {
		String usuario = credentials.getUsername();
		String senha =  ((PasswordCredential) credentials.getCredential()).getValue();
		try {
			Usuario usu = bo.buscarPorNamedQuery("Usuario.buscarPorUsuarioSenha", new Object[]{usuario, senha});
			if(usu != null){
				setStatus(AuthenticationStatus.SUCCESS);
				setUser(new SimpleUser(usu.getUsuario()));
				identity.addRole("operador", "USERS", "GROUP");
			}else{
				setStatus(AuthenticationStatus.FAILURE);
			}
		} catch (BaseException e) {
			log.error("Erro ao buscar usuario no banco");
		}
		
	}
}
